<template>
  <div class="container">
    <div class="box">
      <div class="login-content-left">
        <img :src="loginLeftPng" />
        <div class="login-content-left-mask">
          <div>{{ $t(systemTitle) }}</div>
          <div>{{ $t(systemSubTitle) }}</div>
        </div>
      </div>

      <div class="box-inner">
        <h1>{{ $t('message.system.welcome') }}</h1>
        <!-- 登录表单 -->
        <el-form class="form" @keydown.enter="submit">
          <el-input size="large" v-model="form.user_id" :placeholder="$t('message.system.userName')" type="text"
            maxlength="50">
            <template #prepend>
              <el-icon>
                <User />
              </el-icon>
            </template>
          </el-input>
          <el-input size="large" ref="password" v-model="form.password" :type="passwordType"
            :placeholder="$t('message.system.password')" user_id="password" maxlength="50">
            <template #prepend>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
            <template #append>
              <i class="sfont password-icon" :class="passwordType ? 'system-yanjing-guan' : 'system-yanjing'"
                @click="passwordTypeChange"></i>
            </template>
          </el-input>

          <el-button type="primary" :loading="form.loading" @click="submit" style="width: 100%;" size="large">
            {{ $t('message.system.login') }}
          </el-button>

          <!-- 注册按钮 -->
          <div style="text-align: center; margin-top: 20px;">
            <el-button link type="primary" @click="goToRegister">{{ $t('message.system.register') }}</el-button>
          </div>
        </el-form>

      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { systemTitle, systemSubTitle } from '@/config'
import { ref, reactive, watchEffect } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

import { ElMessage } from 'element-plus'
// import selectLang from '@/layout/components/functionList/word.vue'  // 引入语言切换组件
import loginLeftPng from '@/assets/login/left.jpg';
import { User, Lock } from '@element-plus/icons-vue'
import { sendHeartbeat } from "@/utils/heartbeat";

const store = useStore()
const router = useRouter()
const stuIdFromQuery = ref(localStorage.getItem('user_id')); // 使用 ref 对象


const form = reactive({
  user_id: localStorage.getItem('user_id') || '',
  password: localStorage.getItem('password') || '',
  loading: false
})
const passwordType = ref('password')
const passwordTypeChange = () => {
  passwordType.value === '' ? passwordType.value = 'password' : passwordType.value = ''
}
watchEffect(() => {
  form.user_id = stuIdFromQuery.value;
});
const checkForm = () => {
  return new Promise((resolve, reject) => {
    if (form.user_id === '') {
      ElMessage.warning({
        message: '用户名不能为空',
        type: 'warning'
      });
      return;
    }
    if (form.password === '') {
      ElMessage.warning({
        message: '密码不能为空',
        type: 'warning'
      })
      return;
    }
    resolve(true)
  })
}


const submit = () => {

  checkForm().then(() => {
    const forbidLogin = ref(false)
    form.loading = true
    const params = ref({
      id: form.user_id,
      passWord: form.password,
      ip: '',
      visitorId: '',
    })


    sendHeartbeat(form.user_id, true).then((res: any) => {
      // console.log("sendHeartbeat res = ", res)
      if (res.ok !== true) {
        ElMessage.error({
          message: '同一台电脑禁止登录多个账号，您的账号已被记录。',
          type: 'error'
        });
        console.log('同一台电脑禁止登录多个账号，您的账号已被记录')
        return
      } else {
        console.log('准备登录')
        params.value.ip = res.ip
        params.value.visitorId = res.visitorId
        store.dispatch('user/login', params.value)
          .then((res: any) => {
            console.log('login res = ', res)
            try {

              ElMessage.success({
                message: '登录成功',
                type: 'success',
                showClose: true,
                duration: 5000
              });

              localStorage.setItem('user_id', form.user_id)
              localStorage.setItem('password', form.password)
              location.reload();
            } catch (error) {
              console.error('处理登录成功后的操作时发生错误:', error);
            } finally {
              form.loading = false;
            }
          }).catch((error) => {
            console.error('在Promise链中的其他位置发生错误:', error);
          });
      }
    }).catch(error => {
      console.error('发送心跳请求时发生错误:', error);
      forbidLogin.value = true
    }).finally(() => {

      form.loading = false
    })
  })
}
const goToRegister = () => {
  // 在这里触发路由跳转到注册页面
  router.push('register')
}

</script>

<style lang="scss" scoped>
.container {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: #fff url('@/assets/login/bg.png') no-repeat center;
  overflow: hidden;
  background-size: cover;
  cursor: pointer;
  user-select: none;

  .box {
    width: 1160px;
    display: flex;
    position: absolute;
    left: 50%;
    top: 50%;
    background: white;
    border-radius: 8px;
    transform: translate(-50%, -50%);
    height: 440px;
    overflow: hidden;
    box-shadow: 0 6px 20px 5px rgba(152, 152, 152, 0.1),
      0 16px 24px 2px rgba(117, 117, 117, 0.14);

    .login-content-left {
      position: relative;

      img {
        height: 440px;
      }

      .login-content-left-mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-image: linear-gradient(rgba(0, 204, 222, 0.8), rgba(51, 132, 224, 0.8));
        text-align: center;
        color: #fff;
        font-size: 1.8rem;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        letter-spacing: 2px;

        div:nth-child(1) {
          font-size: 3.5rem;
          margin-bottom: 1em;
        }
      }
    }

    .box-inner {
      width: 500px;

      h1 {
        margin-top: 80px;
        text-align: center;
      }

      .form {
        width: 80%;
        margin: 50px auto 15px;

        .el-input {
          margin-bottom: 20px;
        }

        .password-icon {
          cursor: pointer;
          color: #409eff;
        }
      }

      .fixed-top-right {
        position: absolute;
        top: 10px;
        right: 10px;
      }
    }
  }
}

@media screen and (max-width: 1260px) {
  .login-content-left {
    display: none;
  }

  .box {
    width: 500px !important;
  }
}

@media screen and (max-width: 750px) {

  .container .box,
  .container .box-inner {
    width: 100vw !important;
    height: 100vh;
    box-shadow: none;
    left: 0;
    top: 0;
    transform: none;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    h1 {
      margin-top: 0;
    }

  }
}
</style>
